package zzz.icexxx.excel_demo;

import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * Excel read and write!
 *
 */
public class App {
    public static void main(String[] args) {
        System.out.println("Excel read and write!");
        String xls = "C:/Users/Administrator/Desktop/n/demo.xlsx";
        List<List<String>> list = initData();
        write(xls, list);
        ThreadUtil.sleep(1000);
        List<List<Object>> read = read(xls);
        print(read);
    }

    public static List<List<Object>> read(String xls) {
        ExcelReader reader = ExcelUtil.getReader(xls);
        List<List<Object>> readAll = reader.read();
        return readAll;
    }

    public static void write(String xls, List<List<String>> rows) {
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(xls);
        // 跳过当前行，既第一行，非必须，在此演示用
        // writer.passCurrentRow();
        // 一次性写出内容，强制输出标题
        writer.write(rows, true);
        // 关闭writer，释放内存
        writer.close();
    }

    private static List<List<String>> initData() {
        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
        List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
        List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
        List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
        List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4");
        List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);
        return rows;
    }

    private static void print(List<List<Object>> data) {
        for (int i = 0; i < data.size(); i++) {
            for (int j = 0; j < data.get(i).size(); j++) {
                System.out.print("\t" + data.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}
